#include <stdio.h>
#include <string.h>

// 4M
char table[5000050] = {0};
int str_len = 0;
// 2M
char str[3000000] = {0};
// 10*4M
int res_table[10][1000050] = {{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};

void prepare_table() {
    table[0] = 1;
    table[1] = 1;
    for (int i = 2; i < 2237; i == 2 ? (i = 3) : (i += 2)) {
        for (int n = i; n < 5000050; n += i) {
            if (i != n) table[n] = 1;
        }
    }
    for (int i = 0; i < 5000050; i++) {
        if (i == 1 || i == 0) {
            continue;
        }
        if (table[i] == 0) {
            int len = sprintf(str + str_len, "%d", i);
            str_len += len;
        }
    }
    int res[10] = {0};
    for (int i = 0; i < 1000050; i++) {
        for (int c = 0; c < 10; c++) {
            char ch = '0' + c;
            if (str[i] == ch) {
                res[c]++;
            }
            res_table[c][i] = res[c];
        }
    }
}

int char_count(int start, int end, char c) {
    if (start > end) {
        int tmp = end;
        end = start;
        start = tmp;
    }
    return res_table[c - '0'][end] - res_table[c - '0'][start] + (str[start] == c ? 1 : 0);
}

int main(void) {
    prepare_table();
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        int l, r;
        char d;
        scanf("%d%d %c", &l, &r, &d);
        printf("%d\n", char_count(l - 1, r - 1, d));
    }
    return 0;
}
